import wx
import os
import threading
import EMLseekanddestroyMODULE
import EMLextractor
import EMLDecoder



class CaseNameDialog(wx.Dialog):
    
    def __init__(self, parent, title):
        super(CaseNameDialog, self).__init__(parent=parent, 
            title=title, size=(350, 150))

        panel = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        
        
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)        
        hbox1.Add(wx.StaticText(panel, -1, "Name:" ))


	self.caseNameText = wx.TextCtrl(panel,  size=(300, 28))
        hbox1.Add(self.caseNameText, flag=wx.LEFT, border=5)
        
        
        panel.SetSizer(hbox1)
       
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
	""" poiniendo como id al boton el id = wx.ID_OK implica que este boton se utiliza para ok, se cierra el dialog i se devuelve el codigo wx.ID_OK. los mismo para wx.ID_CANCEL """
        okButton = wx.Button(self,wx.ID_OK, label='Ok')
        closeButton = wx.Button(self,wx.ID_CANCEL, label='Close')

        hbox2.Add(okButton)
        hbox2.Add(closeButton, flag=wx.LEFT, border=5)

        vbox.Add(panel, proportion=1, flag=wx.ALL|wx.EXPAND, border=5)
        vbox.Add(hbox2, flag= wx.ALIGN_CENTER|wx.TOP|wx.BOTTOM, border=10)

        self.SetSizer(vbox)

	self.value = ""
	

        
	#events
	self.caseNameText.Bind(wx.EVT_TEXT,self.SetValue )
        #okButton.Bind(wx.EVT_BUTTON, self.OnClose)
        #closeButton.Bind(wx.EVT_BUTTON, self.OnClose)

    def SetValue(self,e):
	print "SetValue %s" % self.caseNameText.GetValue()
	self.value = self.caseNameText.GetValue()
	        
    def GetValue (self):
	print "getValue"
	return self.value

    def OnClose(self, e):
        self.Destroy()


class MainWindow(wx.Frame):
  def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(1200,400))
        
        #Vars
        self.dirdest =''
        self.filesource = ''
        self.searchtype = ''
	self.casename = ''
        self.running = False
	self.listmodified = False
	self.listsource = ""
	self.defaultCasePath = False
	self.defaultCasePathValue = ""
	self.defaultSavePathValue = ""
	self.opencase = False

	#ENABLING AND DISABLING BUTTONS
	self.extractEnable = False
	self.searchEnable = False
	self.reportEnable = False

	#vars from EMLextractor
	self.decodification = True
        self.overwrite = False
	

	#Steps of workflow
	self.SearchDone = False
	self.ExtractionDone = True

	self.worker = WorkingThread(self, 1, self.filesource, self.dirdest, "",self.casename)

        #Reporting
        self.copyFilesOnReport = False
        
        
        #layout
        self.InitUI()

        
        # A Statusbar in the bottom of the window
        self.CreateStatusBar() 

        # Setting up the menu.
        filemenu= wx.Menu()

        # wx.ID_ABOUT and wx.ID_EXIT are standard IDs provided by wxWidgets.
        menuAbout = filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
        filemenu.AppendSeparator()
        menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
	# Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
        self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.

	
	#Default settings
	#	search type: grep search
	self.searchtype = 'grep'
        self.label4.SetValue(False)
	self.labelGrepSearch.SetValue(True)
	self.labelOnlyFillDB.SetValue(False)
	self.labelSearchDone.SetValue(False)
	self.label4.Enable(False)
	
		
	
        
	
        #case properties
        
        self.dirDestinationButton.Bind(wx.EVT_BUTTON, self.OnDirDest)
        self.control2.Bind(wx.EVT_TEXT,self.OnDirDestTextChange )

	self.caseNameButton.Bind(wx.EVT_BUTTON,self.OnCaseNameNew )
	self.comboDatabaseName.Bind(wx.EVT_COMBOBOX,self.OnCaseNameSelect)

        self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)




	#Extract Tab
        
	self.button1FileSource.Bind(wx.EVT_BUTTON, self.OnFileSourceExtraction)
        #self.button2DirDest.Bind(wx.EVT_BUTTON, self.OnDirDestExtraction)
        self.control1FileSourceText.Bind(wx.EVT_TEXT,self.OnPSTSourceTextChange )
        #self.control2DirDestinationText.Bind(wx.EVT_TEXT,self.OnDirDestExtractionTextChange )
        self.label3Mextraction.Bind(wx.EVT_CHECKBOX, self.OnMextraction)
        self.label4Sextraction.Bind(wx.EVT_CHECKBOX, self.OnSextraction)
        self.label33Base64Decode.Bind(wx.EVT_CHECKBOX, self.OnChooseDecodification)
        self.label34SaveCodificated.Bind(wx.EVT_CHECKBOX, self.OnChooseSaveCodificated)
        self.label44OverwriteCodificated.Bind(wx.EVT_CHECKBOX, self.OnChooseOverwriteCodificated)
        self.button3Extract.Bind(wx.EVT_BUTTON, self.StartExtraction)
	

        #Search Tab
        self.labelGrepSearch.Bind(wx.EVT_CHECKBOX, self.OnGrepSearch)
        self.labelOnlyFillDB.Bind(wx.EVT_CHECKBOX, self.OnOnlyFillDB)
        self.labelSearchDone.Bind(wx.EVT_CHECKBOX, self.OnSearchDoneCheck)
        self.label4.Bind(wx.EVT_CHECKBOX, self.OnPythonSearch)
        self.searchButton.Bind(wx.EVT_BUTTON, self.StartSearch)
	
	self.defaultPathCheckBox.Bind(wx.EVT_CHECKBOX, self.DefaultCasePath)
        self.Bind (wx.EVT_BUTTON, self.OnAdd, id=10)
        self.Bind (wx.EVT_BUTTON, self.OnRemove, id=11)
        self.Bind (wx.EVT_BUTTON, self.OnClear, id=12)
        self.Bind (wx.EVT_BUTTON, self.OpenSearchList, id=13)
        self.Bind (wx.EVT_BUTTON, self.SaveSearchList, id=14)
	self.Bind (wx.EVT_BUTTON, self.SaveAsSearchList, id=15)

	#Report tab
	self.Bind (wx.EVT_BUTTON, self.AddKeywordToListReportTab, id=16)
	self.Bind (wx.EVT_BUTTON, self.RemoveKeywordToListReportTab, id=17)
	self.Bind (wx.EVT_BUTTON, self.LaunchReport, id=18)
	self.Bind (wx.EVT_CHECKBOX, self.SetCopyFilesOnReport, id=19)
	
        

	#other events
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        self.Bind(EVT_ENDWORK, self.EndSearch)
	self.Bind(EVT_ENDWORK2, self.EndExportList)

	self.nb.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.TabChanging)
	self.nb.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.TabChanged)
        
        
	#initializations (disabling of buttons)
	self.DisableButtons()
	self.control2.Enable(True)
	self.dirDestinationButton.Enable(True)
        self.comboDatabaseName.Enable(True)   
	self.caseNameButton.Enable(True)

	#extract, search, and report 
	self.button3Extract.Enable(False)    
        self.searchButton.Enable(False)
        self.reportButton.Enable(False)
        

        
  def InitUI(self):
    

	#root sizer
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        


        
	self.hbox00 = wx.BoxSizer(wx.HORIZONTAL)
	#pnl0 -  ficheros de entrada------------------------------------------------
        self.hbox0 = wx.FlexGridSizer(2, 2, 9, 25)

        
        

	#Tabs
	#ha de ser un panel i tenir com a pare el NoteBook--------------------------------------
        #hbox4 - Search Tab:lista buquedas
        self.hbox4 = wx.BoxSizer(wx.HORIZONTAL)
	#hbox5 - Extract Tab
	self.hbox5 = wx.BoxSizer(wx.HORIZONTAL)
	#hbox6 - Report Tab
	self.hbox6 = wx.BoxSizer(wx.HORIZONTAL)
		
	#Tab container-------------------------------------------------------
	self.nb = wx.Notebook(self)

	#Panel for each Tab
	#-----------------------------------------------------
	self.tabpanelExtract = wx.Panel(self.nb, -1,style= wx.TAB_TRAVERSAL)
	self.tabpanelExtract.SetSizer(self.hbox5)
	self.nb.AddPage(self.tabpanelExtract, "Extract")

	self.tabpanelSearch = wx.Panel(self.nb, -1,style= wx.TAB_TRAVERSAL)
	self.tabpanelSearch.SetSizer(self.hbox4)
	self.nb.AddPage(self.tabpanelSearch, "Search")

	self.tabpanelReport = wx.Panel(self.nb, -1,style= wx.TAB_TRAVERSAL)
	self.tabpanelReport.SetSizer(self.hbox6)
	self.nb.AddPage(self.tabpanelReport, "Report")




	#case and dirdestino ----------------------------------------------------------------------------------

	#caseName
	
        
 	#caseName on combobox
	self.comboDBnameList = []
	self.comboDatabaseName = wx.ComboBox(self, 500, "", (300, 50),
	(160, -1), self.comboDBnameList,
	wx.CB_DROPDOWN | wx.CB_READONLY
	#| wx.TE_PROCESS_ENTER
	#| wx.CB_SORT
	)

	self.caseNameButton = wx.Button(self, id=-1, label='...', size=(30, 28))
        self.caseNameButton.SetToolTip(wx.ToolTip("Open an existing case file"))

        self.minihbox0 = wx.BoxSizer(wx.HORIZONTAL)
        self.minihbox0.Add(self.comboDatabaseName, border=1)  
	self.minihbox0.Add(self.caseNameButton, border=1)   
        self.label0 = wx.StaticText(self, -1, "Database Name" )	

	
        
        #control2 = DirDestino
        self.dirDestinationButton = wx.Button(self, id=-1, label='...', size=(30, 28))
        #        optional tooltip
        self.dirDestinationButton.SetToolTip(wx.ToolTip("choose a destination folder"))
        self.control2 = wx.TextCtrl(self,  size=(300, 28))
        self.minihbox2 = wx.BoxSizer(wx.HORIZONTAL)
        self.minihbox2.Add(self.control2, border=1)
        self.minihbox2.Add(self.dirDestinationButton, border=1)
        self.label2 = wx.StaticText(self, -1, "Case folder" )


        self.hbox0.AddMany([ (self.label2), (self.minihbox2, 1, wx.EXPAND) , (self.label0), (self.minihbox0, 1, wx.EXPAND), self.comboDatabaseName])
	self.hbox0.Layout()

	self.hbox00.Add(self.hbox0,0,flag=wx.LEFT, border=30)

	


#Extract Tab ---------------------------------------------------------------------------------------------------------------------------------    
        extractTabVbox = wx.BoxSizer(wx.VERTICAL)
        
        #hbox1ExtractTab
        self.hbox1ExtractTab = wx.BoxSizer(wx.HORIZONTAL)
        extractTabVbox.Add(self.hbox1ExtractTab, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
        extractTabVbox.Add((-1, 10))

        #hbox2ExtractTab
        self.hbox2ExtractTab = wx.BoxSizer(wx.HORIZONTAL)
        extractTabVbox.Add(self.hbox2ExtractTab, flag=wx.LEFT | wx.TOP, border=10)
        extractTabVbox.Add((-1, 10))
        
        
        #hbox3ExtractTab
        self.hbox3ExtractTab = wx.BoxSizer(wx.HORIZONTAL)
        extractTabVbox.Add(self.hbox3ExtractTab, flag=wx.LEFT | wx.TOP, border=10)
        extractTabVbox.Add((-1, 10))
        
        #hbox4ExtractTab
        self.hbox4ExtractTab = wx.BoxSizer(wx.HORIZONTAL)
        extractTabVbox.Add(self.hbox4ExtractTab, flag=wx.LEFT | wx.TOP, border=10)
        extractTabVbox.Add((-1, 10))
        
        #hbox5ExtractTab
        self.hbox5ExtractTab = wx.BoxSizer(wx.HORIZONTAL)
        extractTabVbox.Add(self.hbox5ExtractTab, flag=wx.LEFT | wx.TOP, border=10)
        extractTabVbox.Add((-1, 10))
        





        fgs = wx.FlexGridSizer(2, 2, 9, 25)
        #controls1
        self.button1FileSource = wx.Button(self.tabpanelExtract, id=-1, label='...', size=(30, 28))
        #         optional tooltip
        self.button1FileSource.SetToolTip(wx.ToolTip("choose a folder with pst or ost files"))
        self.control1FileSourceText = wx.TextCtrl(self.tabpanelExtract,  size=(300, 28))
        self.minihbox1ExtractTab = wx.BoxSizer(wx.HORIZONTAL)
        self.minihbox1ExtractTab.Add(self.control1FileSourceText, border=1)
        self.minihbox1ExtractTab.Add(self.button1FileSource, border=1)
        
        self.label1ExtractTab = wx.StaticText(self.tabpanelExtract, -1, "pst folder" , wx.Point(15, 30))
        
	"""        
	#control2DirDestinationText
        self.button2DirDest = wx.Button(self.tabpanelExtract, id=-1, label='...', size=(30, 28))
        #        optional tooltip
        self.button2DirDest.SetToolTip(wx.ToolTip("choose a destination folder"))
        self.control2DirDestinationText = wx.TextCtrl(self.tabpanelExtract,  size=(300, 28))
        self.minihbox2ExtractTab = wx.BoxSizer(wx.HORIZONTAL)
        self.minihbox2ExtractTab.Add(self.control2DirDestinationText, border=1)
        self.minihbox2ExtractTab.Add(self.button2DirDest, border=1)
        
        self.label2ExtractTab = wx.StaticText(self.tabpanelExtract, -1, "Destination folder" , wx.Point(15, 30))
	
        fgs.AddMany([(self.label1ExtractTab), (self.minihbox1ExtractTab, 1, wx.EXPAND), 
            (self.label2ExtractTab), (self.minihbox2ExtractTab, 1, wx.EXPAND)])
	"""
	fgs.AddMany([(self.label1ExtractTab), (self.minihbox1ExtractTab, 1, wx.EXPAND)])
        
	self.hbox1ExtractTab.Add(fgs, proportion=1, flag=wx.ALL|wx.EXPAND, border=15)





        #checkbox here
        self.label3Mextraction = wx.CheckBox(self.tabpanelExtract, -1, "M extraction"  )
        self.label3Mextraction.SetValue(True)
        self.label4Sextraction = wx.CheckBox(self.tabpanelExtract, -1, "S extraction" )
        self.label4Sextraction.SetValue(False)
        #disabled quitar en un futuro?
        self.label4Sextraction.Enable(False)
        self.label3Mextraction.Enable(False)
        self.hbox2ExtractTab.Add(self.label3Mextraction, border=8)
        self.hbox2ExtractTab.Add(self.label4Sextraction, border=8)
        
        #checkbox here
        self.label33Base64Decode = wx.CheckBox(self.tabpanelExtract, -1, "Decode base64"  )
        self.label33Base64Decode.SetValue(True)
        self.hbox3ExtractTab.Add(self.label33Base64Decode, border=8)

        
        #checkbox here
        self.label34SaveCodificated = wx.CheckBox(self.tabpanelExtract, -1, "Save base64 encoded files"  )
        self.label34SaveCodificated.SetValue(True)
        self.label44OverwriteCodificated = wx.CheckBox(self.tabpanelExtract, -1, "Erase base64 encoded files" )
        self.label44OverwriteCodificated.SetValue(False)
        self.hbox4ExtractTab.Add(self.label34SaveCodificated, border=8)
        self.hbox4ExtractTab.Add(self.label44OverwriteCodificated, border=8)
        
        
        #button Search
        self.button3Extract = wx.Button(self.tabpanelExtract, id=-1, label='Extract', size=(100, 28))
        self.button3Extract.SetToolTip(wx.ToolTip("Start extraction"))
        self.hbox5ExtractTab.Add(self.button3Extract, border=8)
        
        
        self.hbox5.Add(extractTabVbox, 0,flag=wx.LEFT, border=1)



#Search Tab ---------------------------------------------------------------------------------------------------------------------------------
            #hbox1 - boton buscar y opciones de busqueda------------------------------------------------
        self.hbox1 = wx.BoxSizer(wx.VERTICAL)
	self.hbox11 = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox12 = wx.BoxSizer(wx.HORIZONTAL)
    
	#Search button and config checkboxes -------------------------------------------------------------------------------------------------------------------------------------
	self.searchButton = wx.Button(self.tabpanelSearch, id=-1, label='Search', size=(100, 28))
        self.searchButton.SetToolTip(wx.ToolTip("Start searching"))
        self.labelGrepSearch = wx.CheckBox(self.tabpanelSearch, -1, "Grep search"  )
        self.label4 = wx.CheckBox(self.tabpanelSearch, -1, "Python regexp search" )
        self.labelOnlyFillDB = wx.CheckBox(self.tabpanelSearch, -1, "Only Fill Database" )
        self.labelSearchDone = wx.CheckBox(self.tabpanelSearch, -1, "Only Create Reports" )
	self.hbox1.Add(self.searchButton, border=1)
	self.hbox1.Add((60, 10))
        self.hbox11.Add(self.labelGrepSearch, border=10)
	self.hbox11.Add((4, 10))
        self.hbox11.Add(self.label4, border=1)
        #self.hbox11.Add((-1, 10))
        self.hbox12.Add(self.labelOnlyFillDB, border=1)
        self.hbox12.Add((4, 10))
        self.hbox12.Add(self.labelSearchDone, border=1)
	self.hbox1.Add(self.hbox11, border=1)
	self.hbox1.Add(self.hbox12, border=1)



	vbox0 = wx.BoxSizer(wx.HORIZONTAL)
	vbox1 = wx.BoxSizer(wx.VERTICAL)

        #vbox3 = wx.GridSizer(3,2,0,0)
	vbox3 = wx.BoxSizer(wx.VERTICAL)
        vbox4 = wx.BoxSizer(wx.HORIZONTAL )
	vbox5 = wx.BoxSizer(wx.HORIZONTAL )
	vbox05 = wx.BoxSizer(wx.VERTICAL )
        
	#panel botones open , save, save as
        self.subpanel0 = wx.Panel(self.tabpanelSearch, -1, style=wx.SIMPLE_BORDER | wx.TAB_TRAVERSAL)
        vbox5.Add(wx.Button(self.subpanel0, 13, 'Open'),   0, wx.LEFT, 2)
        vbox5.Add(wx.Button(self.subpanel0, 14, 'Save'), 0, wx.LEFT, 2)
        vbox5.Add(wx.Button(self.subpanel0, 15, 'Save As'), 0, wx.LEFT, 2)
	
	vbox05.Add(vbox5,0)
	vbox05.Add((2,2))


	self.labelOpenedFileSearchList = wx.TextCtrl(self.subpanel0)
	self.labelOpenedFileSearchList.SetEditable(False)
	self.labelOpenedFileSearchList.SetValue("no file")
	self.labelOpenedFileSearchList.SetValue("no file")


	vbox05.Add(self.labelOpenedFileSearchList,0,wx.EXPAND | wx.BOTTOM )
	#subpanel0.SetAutoLayout(True)        
	self.subpanel0.SetSizer(vbox05)
        #subpanel0.Layout()


        #panel datos busqueda
        self.subpanel1 = wx.Panel(self.tabpanelSearch, -1, style=wx.SIMPLE_BORDER | wx.TAB_TRAVERSAL)
        self.tc1 = wx.TextCtrl(self.subpanel1,  size=(300, 28))
        self.tc2 = wx.TextCtrl(self.subpanel1,  size=(300, 28))
	self.tc3 = wx.TextCtrl(self.subpanel1,  size=(300, 28))

	vbox31 = wx.BoxSizer(wx.HORIZONTAL )
	vbox32 = wx.BoxSizer(wx.HORIZONTAL )
	vbox33 = wx.BoxSizer(wx.HORIZONTAL )
	vbox34 = wx.BoxSizer(wx.HORIZONTAL )

	vbox31.AddMany([ (wx.StaticText(self.subpanel1, -1, 'Keyword'),0, wx.LEFT),(10,10),(self.tc1, 1,wx.EXPAND)])
	vbox32.AddMany([(wx.StaticText(self.subpanel1, -1, 'Regexp'),0, wx.LEFT),(18,10), (self.tc2, 1,wx.EXPAND)])
	vbox33.AddMany([ (wx.StaticText(self.subpanel1, -1, 'Path'),0, wx.LEFT),(38,10),(self.tc3, 1,wx.EXPAND)])
	self.defaultPathCheckBox = wx.CheckBox(self.subpanel1, -1, "Default Case Path" )	
	vbox34.Add(self.defaultPathCheckBox,0,wx.ALIGN_CENTER_HORIZONTAL)

        vbox3.AddMany([ (vbox31,0, wx.LEFT |wx.EXPAND ),(vbox32,0, wx.LEFT|wx.EXPAND),(vbox33,0, wx.LEFT|wx.EXPAND),(vbox34,0, wx.LEFT|wx.EXPAND)])
	#subpanel1.SetAutoLayout(True)
        self.subpanel1.SetSizer(vbox3)
	#subpanel1.Layout()
        
        #panel botones anadir quitar
        
        vbox4.Add(wx.Button(self.subpanel1, 10, 'Add'),   0, wx.ALIGN_CENTER| wx.TOP, 2)
        vbox4.Add(wx.Button(self.subpanel1, 11, 'Remove'), 0, wx.ALIGN_CENTER|wx.TOP, 2)
        vbox4.Add(wx.Button(self.subpanel1, 12, 'Clear'), 0, wx.ALIGN_CENTER| wx.TOP, 2)
	vbox3.Add(vbox4, 0,wx.ALIGN_CENTER_HORIZONTAL, border=1)




        

        #panel lista con las busquedas
        self.lc = wx.ListCtrl(self.tabpanelSearch, size=(500,600), style=wx.LC_REPORT | wx.TAB_TRAVERSAL)
	#coincidira con el "output" (en modo fichero de resultado busqueda por cada keyword)        
	self.lc.InsertColumn(0, 'Keyword')
	#coincidira con el keyword
        self.lc.InsertColumn(1, 'Regexp')
	#ruta carpeta donde buscar recursivamente
        self.lc.InsertColumn(2, 'Path')
        self.lc.SetColumnWidth(0, 140)
        self.lc.SetColumnWidth(1, 253)
	self.lc.SetColumnWidth(2, 253)



	vbox1.Add(self.subpanel0, 0, wx.EXPAND | wx.ALL, 3)
        vbox1.Add(self.subpanel1, 0, wx.EXPAND | wx.ALL, 3)
        #vbox1.Add(self.subpanel2, 0, wx.EXPAND | wx.ALL, 3)
	vbox1.Add(self.lc, 0,flag=wx.LEFT, border=1)

	vbox0.Add(vbox1,0,flag=wx.LEFT, border=1)
	vbox0.Add(self.hbox1,0,flag=wx.LEFT, border=20)
       
        self.hbox4.Add(vbox0, 0,flag=wx.LEFT, border=1)
	self.hbox4.Add((-1, 10))
        
	self.hbox4.Layout()

	#Report Tab -------------------------------------------------------------------------------------------------------
	#self.tabpanelReport ,self.hbox6 
	
	#listCtrl amb les busquedas, o sigui keywords
		#init al clickar a la pestanya report 
	self.reportKeywordAllLC = wx.ListCtrl(self.tabpanelReport, size=(200,600), style=wx.LC_REPORT)
	self.reportKeywordAllLC.InsertColumn(0, 'Available Keywords')
        self.reportKeywordAllLC.SetColumnWidth(0, 210)
	self.hbox6.Add(self.reportKeywordAllLC, 0,flag=wx.LEFT, border=1)

	#listCtrl amb keywords del report
	#	boto afegir keyword a report
	#	boto remove keyword a report
	
	vbox40 = wx.BoxSizer(wx.VERTICAL )
	
	self.reportKeywordSelectionLC = wx.ListCtrl(self.tabpanelReport, size=(200,400), style=wx.LC_REPORT)
	self.reportKeywordSelectionLC.InsertColumn(0, 'Choosen Keywords')
        self.reportKeywordSelectionLC.SetColumnWidth(0, 210)
	vbox40.Add(self.reportKeywordSelectionLC, 0,flag=wx.LEFT, border=1)

	vbox41 = wx.BoxSizer(wx.HORIZONTAL)
	vbox41.Add(wx.Button(self.tabpanelReport, 16, 'Add'),   0, wx.ALIGN_CENTER| wx.TOP, 2)
        vbox41.Add(wx.Button(self.tabpanelReport, 17, 'Remove'), 0, wx.ALIGN_CENTER|wx.TOP, 2)

	vbox40.Add(vbox41, 0,flag=wx.LEFT, border=1)
	
	
	

	#	comboBox menu combinacio OR , AND
	# com fer combinacions mes complicades???.....futurament
	sampleList = ['OR', 'AND', 'NOT']
	labelcb = wx.StaticText(self.tabpanelReport, -1, "Combination operator", (8, 10))
	# This combobox is created with a preset list of values.
	self.cb = wx.ComboBox(self.tabpanelReport, 500, "OR", (90, 50),
	(160, -1), sampleList,
	wx.CB_DROPDOWN | wx.CB_READONLY
	#| wx.TE_PROCESS_ENTER
	#| wx.CB_SORT
	)
	vbox40.Add(labelcb, 0,flag=wx.LEFT, border=1)
	vbox40.Add(self.cb, 0,flag=wx.LEFT, border=1)

	self.hbox6.Add(vbox40, 0,flag=wx.LEFT, border=1)

	#	boto escriure report
	vbox42 = wx.BoxSizer(wx.VERTICAL )
	self.reportButton = wx.Button(self.tabpanelReport, 18, 'Write Report')
	vbox42.Add(self.reportButton,   0, wx.ALIGN_CENTER| wx.TOP, 2)
	
	vbox42.Add(wx.CheckBox(self.tabpanelReport, 19, 'Copy files'),   0, wx.ALIGN_CENTER| wx.TOP, 2)
	

	self.hbox6.Add(vbox42, 0,flag=wx.LEFT, border=1)

	# final layout -----------------------------------------------------------------------------------------------------------
	
        self.vbox.Add((10, 10))
        self.vbox.Add(self.hbox00, 0,flag=wx.EXPAND, border=10)
        self.vbox.Add((10, 50))
        self.vbox.Add(self.nb, 0,flag=wx.EXPAND, border=10)
        self.vbox.Add((10, 10))

        self.vbox.Layout()


	


	self.SetPosition(wx.Point(0,0))
 	self.SetSize(wx.Size(950,860))
 	self.SetTitle('EMLseekanddestroy')
	self.SetSizer(self.vbox)
	self.Layout()
        self.Show(True)



 
  #------EVENT ACTIONS---------------------------------------------------------------------------------      
  #------EVENT ACTIONS---------------------------------------------------------------------------------      


# REPORT tab ----------------------------------------------------------------------------

  def SetCopyFilesOnReport(self,event):
    if (self.copyFilesOnReport):
      self.copyFilesOnReport = False
      print "copyFilesOnReport False"
    else:
      self.copyFilesOnReport = True
      print "copyFilesOnReport True"

  def LaunchReport(self,event):
    if (self.reportKeywordSelectionLC.GetItemCount() > 0 ):
	   print "[LaunchReport]"
	   keywordlist = []
	   # Gather all the list items in the listCtrl
           for row in range(self.reportKeywordSelectionLC.GetItemCount()):
              keywordlist.append(self.reportKeywordSelectionLC.GetItem(row, 0).GetText())

	   combination = self.cb.GetValue()

	   self.running = True
	   #disable controls
	   self.DisableButtons()
	   try:
		self.worker = WorkingThreadReportCreate(self, 1, self.filesource, self.dirdest, "createreport",self.casename,keywordlist, combination,self.copyFilesOnReport)
		self.worker.start()
	   except Exception, e:
		print "Error starting thread %s " % e

  def AddKeywordToListReportTab(self,event):
    #get selected item
    i1 = self.reportKeywordAllLC.GetFocusedItem()
    itemi = self.reportKeywordAllLC.GetItem(i1,0)
    item = itemi.GetText()
    print "item  : %s " % item

    num_items = self.reportKeywordSelectionLC.GetItemCount()
    self.reportKeywordSelectionLC.InsertStringItem(num_items, item)

    num_items = self.reportKeywordSelectionLC.GetItemCount()
    if (num_items > 0):
	self.reportButton.Enable(True)
	self.reportEnable = True
    else:
	self.reportButton.Enable(False)
	self.reportEnable = False

  
  def RemoveKeywordToListReportTab(self, event):
    index = self.reportKeywordSelectionLC.GetFocusedItem()
    self.reportKeywordSelectionLC.DeleteItem(index)

    num_items = self.reportKeywordSelectionLC.GetItemCount()
    if (num_items > 0):
	self.reportButton.Enable(True)
	self.reportEnable = True
    else:
	self.reportButton.Enable(False)
	self.reportEnable = False
    

  def TabChanging(self,e):
	if (self.running == True):
		e.Veto()
		dlg = wx.MessageDialog( self, "Please Wait", "Running", wx.OK)
		result = dlg.ShowModal()
		dlg.Destroy()
	elif (self.opencase == False):
		e.Veto()
		dlg = wx.MessageDialog( self, "Please open a case", "No case found", wx.OK)
		result = dlg.ShowModal()
		dlg.Destroy()
		

  def TabChanged(self,e):

	if (self.nb.GetSelection() == 2 and self.SearchDone):
		#open db connectiona nd retrieve keywords
		#then put them on the control list -> on the End
		self.running = True
		#disable controls
		self.DisableButtons()
		#print "starting search %s %s %s %s" % (self.filesource, self.dirdest, "getkeywords",self.casename)
		try:
		  
		  self.worker = WorkingThread(self, 1, self.filesource, self.dirdest, "getkeywords",self.casename)
		  self.worker.start()
		except Exception, e:
		  print "Error starting thread %s " % e

  def EndRetrieveKeywordsSearch (self, e):
        #fill the list ctrl
	print "END RETRIEVEKEYWORDS!! and worker.typesearch  = %s " % self.worker.searchtype
	self.worker.result
	if (self.worker.result != "error" and type(self.worker.result).__name__=="list" ):
		self.reportKeywordAllLC.DeleteAllItems()
		#print "type of worker.result: %s " % type(self.worker.result).__name__

		self.reportButton.Enable(False)	
		self.reportEnable = False	
		
		for kwrd in self.worker.result:
			print "type of kwrd elem in list: %s " % type(kwrd).__name__
		 	num_items = self.reportKeywordAllLC.GetItemCount()
			self.reportKeywordAllLC.InsertStringItem(num_items, kwrd[0])
	


  #SEARCH tab -----------------------------------------------------------------------------------

  def DefaultCasePath(self,e):
	if (self.defaultCasePath):
		self.defaultCasePath = False
		self.tc3.Enable(True)

	else:
		self.defaultCasePath = True
		self.tc3.Enable(False)
		self.tc3.SetValue(self.defaultCasePathValue)


  def OnAbout(self,e):
        # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
        dlg = wx.MessageDialog( self, "An EML analyzer", "About EMLseekanddestroy", wx.OK)
        dlg.ShowModal() # Show it
        dlg.Destroy() # finally destroy it when finished.

  def OnExit(self,e):
        if (self.running):
          dlg = wx.MessageDialog( self, "The search is still running. Do you really want to quit?", "Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
          result = dlg.ShowModal()
          dlg.Destroy()
          if result == wx.ID_OK:
            self.Destroy()
        else:
          self.Destroy()

        
  def OnDirDest (self,e):
        """ Destination folder"""
        #dialog = wx.DirDialog(None, "Choose a directory:",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        dlg = wx.DirDialog(self, "Choose a directory", style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON|wx.MAXIMIZE_BOX|wx.THICK_FRAME)
        if dlg.ShowModal() == wx.ID_OK:
            self.dirdest = dlg.GetPath()
            self.control2.SetValue(self.dirdest) 
	    self.defaultCasePathValue = self.dirdest + '/eml'
	    self.defaultSavePathValue = self.dirdest
	    """
	    self.dirdest =''
	    self.casename = ''
	    self.defaultCasePath = False
	    self.defaultCasePathValue = ""
	    self.defaultSavePathValue = ""
	    self.opencase = False
	    """
	    self.CaseNameFillComboBox(self.CaseNameFindDBs(self.defaultSavePathValue))


	    if (not(self.casename == '')):
		self.opencase = True
		self.EnableTabs()
        dlg.Destroy()
	
    
  def OnDirDestTextChange (self,e):
        self.dirdest = self.control2.GetValue()
	self.defaultCasePathValue = self.dirdest + '/eml'
	self.defaultSavePathValue = self.dirdest
        print (" dirdest = "+self.dirdest+" filesource= "+self.filesource +" searchtype = "+self.searchtype)
	"""
	self.dirdest =''
	self.casename = ''
	self.defaultCasePath = False
	self.defaultCasePathValue = ""
	self.defaultSavePathValue = ""
	self.opencase = False
	"""

	self.CaseNameFillComboBox(self.CaseNameFindDBs(self.defaultSavePathValue))

	if (not(self.casename == '')):
		self.opencase = True
		self.EnableTabs()
		
			
  #database name functions----------------------
  def CaseNameFindDBs (self , dirdest):
	""" extrae lista de ficheros *.db" """
	#listar ficheros de un directorio
        dirList=os.listdir(dirdest)
	resultado = []

        for fname in dirList:
        	nombreext = os.path.basename(fname) 
		nombreyext = os.path.splitext(nombreext)
		if (len(nombreyext) > 1 and nombreyext[1] == ".db"):
	        	resultado.append(nombreyext[0])

	return sorted(resultado)

  def CaseNameFillComboBox (self,listDBnames):
	""" rellena el combo box con la lista de db's """
	self.comboDatabaseName.SetItems(listDBnames)
	self.comboDatabaseName.SetSelection(0)

  def CaseNameAddNewDb (self,dbname):
	""" anyade al combobox la nueva db i pone SetSelection a su posicion """
	self.comboDatabaseName.Append(dbname)
	self.comboDatabaseName.SetStringSelection(dbname)

  def OnCaseNameSelect (self,e):
	""" combobox selection changed """
	self.casename = self.comboDatabaseName.GetValue()

	if (not(self.defaultSavePathValue == '')):
		self.opencase = True
		self.EnableTabs()

  def OnCaseNameNew (self,e):
        """ case/database new database name"""
        
	dlg = CaseNameDialog(self, "New Database Name")
	returnval = dlg.ShowModal()
	#print "returnval = %d, and ID_OK = %d and ID_CANCEL = %d and ID_ANY = %d " % (returnval,wx.ID_OK, wx.ID_CANCEL, wx.ID_ANY)
	if  returnval == wx.ID_OK:
	    self.CaseNameAddNewDb(dlg.GetValue())
	    self.casename = dlg.GetValue()
	    if (not(self.defaultSavePathValue == '')):
		self.opencase = True
		self.EnableTabs()
	
	dlg.Destroy()
        
 
      
  #----------------------DISABLE ENABLE CONTROLS------------------------------------------------------------
  def DisableButtons (self):
        #disable controls
        #self.button1.Enable(False)
        self.dirDestinationButton.Enable(False)
        self.comboDatabaseName.Enable(False) 
	self.caseNameButton.Enable(False)
        #self.control1.Enable(False)
        self.control2.Enable(False)

	#Search controls
        self.searchButton.Enable(False)
        self.labelGrepSearch.Enable(False)
        self.labelOnlyFillDB.Enable(False)
        self.labelSearchDone.Enable(False)
	#self.label4.Enable(False)

	#Extraction controls
        self.button1FileSource.Enable(False)
        #self.button2DirDest.Enable(False)
        self.button3Extract.Enable(False)
        
        self.control1FileSourceText.Enable(False)
        #self.control2DirDestinationText.Enable(False)
        
        self.label3Mextraction.Enable(False)
        self.label4Sextraction.Enable(False)
       

	#Report controls
	self.reportButton.Enable(False)

        #event

 
        buttono = self.FindWindowById(10)
        buttono.Enable(False)
        buttono = self.FindWindowById(11)
        buttono.Enable(False)
        buttono = self.FindWindowById(12)
        buttono.Enable(False)
        buttono = self.FindWindowById(13)
        buttono.Enable(False)
        buttono = self.FindWindowById(14)
        buttono.Enable(False)
	buttono = self.FindWindowById(15)
        buttono.Enable(False)
        buttono = self.FindWindowById(16)
        buttono.Enable(False)
        buttono = self.FindWindowById(17)
        buttono.Enable(False)
        buttono = self.FindWindowById(19)
        buttono.Enable(False)
        
	



    
  def EnableButtons (self):
        #disable controls
        #self.button1.Enable(True)
        self.dirDestinationButton.Enable(True)
        self.comboDatabaseName.Enable(True)   
	self.caseNameButton.Enable(True)     
        #self.control1.Enable(True)
        self.control2.Enable(True)


	#search related buttons
	if (self.searchEnable):
	        self.searchButton.Enable(True)        
        self.labelGrepSearch.Enable(True)
        self.labelOnlyFillDB.Enable(True)
        self.labelSearchDone.Enable(True)
        #self.label4.Enable(True)

        #Extraction controls
        self.button1FileSource.Enable(True)
        #self.button2DirDest.Enable(True)
	if (self.extractEnable):
	        self.button3Extract.Enable(True)
        self.control1FileSourceText.Enable(True)
        #self.control2DirDestinationText.Enable(True)
        self.label3Mextraction.Enable(True)
        self.label4Sextraction.Enable(True)
        

	#Report Controls
	if (self.reportEnable):
		self.reportButton.Enable(True)
	#other
        buttono = self.FindWindowById(10)
        buttono.Enable(True)
        buttono = self.FindWindowById(11)
        buttono.Enable(True)
        buttono = self.FindWindowById(12)
        buttono.Enable(True)
        buttono = self.FindWindowById(13)
        buttono.Enable(True)
        buttono = self.FindWindowById(14)
        buttono.Enable(True)
	buttono = self.FindWindowById(15)
        buttono.Enable(True)
        buttono = self.FindWindowById(16)
        buttono.Enable(True)
        buttono = self.FindWindowById(17)
        buttono.Enable(True)
        buttono = self.FindWindowById(19)
        buttono.Enable(True)
  

  def EnableTabs (self):
        #disable controls
        #self.button1.Enable(True)
        self.dirDestinationButton.Enable(True)
        

        self.comboDatabaseName.Enable(True)   
	self.caseNameButton.Enable(True)     
        self.control2.Enable(True)
        


        #Extraction controls
        self.button1FileSource.Enable(True)

        self.control1FileSourceText.Enable(True)
        self.label3Mextraction.Enable(True)
        self.label4Sextraction.Enable(True)
        

	#Search controls

        self.labelGrepSearch.Enable(True)
        self.labelOnlyFillDB.Enable(True)
        self.labelSearchDone.Enable(True)

	#Report controls
        buttono = self.FindWindowById(10)
        buttono.Enable(True)
        buttono = self.FindWindowById(11)
        buttono.Enable(True)
        buttono = self.FindWindowById(12)
        buttono.Enable(True)
        buttono = self.FindWindowById(13)
        buttono.Enable(True)
        buttono = self.FindWindowById(14)
        buttono.Enable(True)
	buttono = self.FindWindowById(15)
        buttono.Enable(True)
        buttono = self.FindWindowById(16)
        buttono.Enable(True)
        buttono = self.FindWindowById(17)
        buttono.Enable(True)

        buttono = self.FindWindowById(19)
        buttono.Enable(True)
  
  #---------------------_SEARCH BUTTONS----------------------------------------------------------------------




  def OnSearchDoneCheck (self,e):
        self.searchtype = ''
        self.SearchDone = True
        self.label4.SetValue(False)
        self.labelGrepSearch.SetValue(False)
        self.labelOnlyFillDB.SetValue(False)
        #self.labelSearchDone.SetValue(True)
        print (" marking searchdone = " + self.SearchDone)
    
  def OnOnlyFillDB (self,e):
        self.searchtype = 'dbwork'
        self.label4.SetValue(False)
        self.labelGrepSearch.SetValue(False)
        self.labelSearchDone.SetValue(False)
        print (" dirdest = "+self.dirdest+" filesource= "+self.filesource +" searchtype = "+self.searchtype)

  def OnGrepSearch (self,e):
        self.searchtype = 'grep'
        self.label4.SetValue(False)
        self.labelOnlyFillDB.SetValue(False)
        self.labelSearchDone.SetValue(False)
        print (" dirdest = "+self.dirdest+" filesource= "+self.filesource +" searchtype = "+self.searchtype)

        
  def OnPythonSearch (self,e):
        self.searchtype = 'python'
        self.labelGrepSearch.SetValue(False)
        self.labelOnlyFillDB.SetValue(False)
        self.labelSearchDone.SetValue(False)
        print (" dirdest = "+self.dirdest+" filesource= "+self.filesource +" searchtype = "+self.searchtype)





  def StartSearch (self,e):
    
        self.running = True

	
	

        # Si ListCtrl se ha modificado preguntar si se quiere guardar y utilizar esta lista
	if (self.listmodified):
		dlg = wx.MessageDialog( self, "You must save the keyword list first", "Save changes", wx.OK)
          	result = dlg.ShowModal()
          	dlg.Destroy()
		self.running = False
		return
          	#if result == wx.ID_OK:
            	#	self.Destroy()

         
    
        #disable controls
        self.DisableButtons()
	print "starting search %s %s %s %s" % (self.filesource, self.dirdest, self.searchtype,self.casename)
        try:
	 
          self.worker = WorkingThread(self, 1, self.filesource, self.dirdest, self.searchtype,self.casename)
          self.worker.start()
        except Exception, e:
          print "Error starting thread %s " % e

  def EndExportList (self, e):        
	""" Cuandoo un thread tipo workerThreadListExport acaba """ 

	
 
	dlg = wx.MessageDialog( self, "The work is done!", "Work done", wx.OK)
        result = dlg.ShowModal()
        dlg.Destroy()
	
	self.running = False

	#enable controls
	self.searchEnable=True
	self.EnableButtons()
	self.SearchDone = True

	      
  def EndSearch (self, e):
        print ("[EndSearch from WorkingThread ]Search is over, worker.searchtype = %s" % self.worker.searchtype)
        
	if (self.worker.searchtype == "getkeywords"):
		self.EndRetrieveKeywordsSearch(e)
			

	dlg = wx.MessageDialog( self, "The work [" + self.worker.searchtype +   "] is done!", "Work done", wx.OK)
        result = dlg.ShowModal()
        dlg.Destroy()
	
	self.running = False

	#enable controls
	self.EnableButtons()
	self.SearchDone = True



  
  
  #Events on list of regular expressions------------------------------
  def OnAdd(self, event):
    if not self.defaultCasePath and (not self.tc1.GetValue() or not self.tc2.GetValue() or not self.tc3.GetValue()):
      return

    if self.defaultCasePath and (not self.tc1.GetValue() or not self.tc2.GetValue() ):
      return

    num_items = self.lc.GetItemCount()
    self.lc.InsertStringItem(num_items, self.tc1.GetValue())
    self.lc.SetStringItem(num_items, 1, self.tc2.GetValue())
    if (self.defaultCasePath):
	self.lc.SetStringItem(num_items, 2, self.defaultCasePathValue)
    else:
    	self.lc.SetStringItem(num_items, 2, self.tc3.GetValue())
    self.tc1.Clear()
    self.tc2.Clear()
    self.tc3.Clear()

    self.listmodified = True

    self.searchButton.Enable(True)
    self.searchEnable = True

  
  def OnRemove(self, event):
    index = self.lc.GetFocusedItem()
    self.lc.DeleteItem(index)

    self.listmodified = True
    if (self.lc.GetItemCount() < 1):
	self.searchButton.Enable(False)
	self.searchEnable = False


  def OnClear(self, event):
    self.lc.DeleteAllItems()
    self.listmodified = False
    self.listsource = ""
    self.labelOpenedFileSearchList.SetValue(self.listsource)
    self.searchButton.Enable(False)
    self.searchEnable = False
        


  #---------IMPORT EXPORT LIST BUTTONS---------------------------------------------------------
  def OpenSearchList (self,e):
    
        self.running = True
    
	if (self.listmodified):
		dlg = wx.MessageDialog( self, "Save the current list?", "Save changes", wx.OK|wx.CANCEL)
		result = dlg.ShowModal()
		dlg.Destroy()
		if result == wx.ID_OK:
			if (self.listsource != ""):
				self.SaveSearchList(e)
			else:
				self.SaveAsSearchList(e)
			


	#dialog filesource, then save that value to listsource
	self.listsource=""
	#dialog = wx.DirDialog(None, "Choose a directory:",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
	dlg = wx.FileDialog(self, "Choose a list file", self.defaultSavePathValue,"","*",style=wx.DD_DEFAULT_STYLE | wx.FD_OPEN |wx.MAXIMIZE_BOX|wx.THICK_FRAME)
	if dlg.ShowModal() == wx.ID_OK:
	    self.listsource = dlg.GetPath()
	dlg.Destroy()

	try:
	
		if (not (self.listsource == "")):
	    	  self.labelOpenedFileSearchList.SetValue(self.listsource)
		  self.filesource = self.listsource
		  #disable controls
		  self.DisableButtons()
		  try:
		    worker = WorkingThreadListExport(self, 1, self.listsource, 1,self.lc)
		    worker.start()
		    
		  except Exception, e:
		    print "Error starting thread %s " % e
	except Exception, e:
		print "Error Opening search list: %s " % e

	

	
	
  def SaveSearchList (self,e):
    
        self.running = True

        if (self.listsource != ""):
          #disable controls
	  self.filesource = self.listsource
          self.DisableButtons()
          try:
            worker = WorkingThreadListExport(self, 1, self.listsource, 0,self.lc)
            worker.start()
	    self.listmodified = False
          except Exception, e:
            print "Error starting thread %s " % e
	else:
	  self.SaveAsSearchList(e)
          

  
  def SaveAsSearchList (self,e):
    
        self.running = True

        #dialog filesource, then save that value to listsource
        self.listsource=""
        #dialog = wx.DirDialog(None, "Choose a directory:",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        dlg = wx.FileDialog(self, "Choose a list file", self.defaultSavePathValue, "" , "*", style=wx.DD_DEFAULT_STYLE | wx.FD_SAVE |wx.MAXIMIZE_BOX|wx.THICK_FRAME)
        if dlg.ShowModal() == wx.ID_OK:
            self.listsource = dlg.GetPath()
        dlg.Destroy()
        
        if (self.listsource != ""):
    
	  self.filesource = self.listsource
          #disable controls
          self.DisableButtons()
          try:
            worker = WorkingThreadListExport(self, 1, self.listsource, 0,self.lc)
            worker.start()
	    self.listmodified = False
          except Exception, e:
            print "Error starting thread %s " % e
          
#  Extraction functions ------------------------------------------------------------------------------------------------

   
  def OnFileSourceExtraction (self,e):
        """ Source File"""
        self.filesource = ''
        #dialog = wx.DirDialog(None, "Choose a directory:",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        dlg = wx.DirDialog(self, "Choose a file or directory", self.defaultSavePathValue,style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON |wx.MAXIMIZE_BOX|wx.THICK_FRAME)
        if dlg.ShowModal() == wx.ID_OK:
            self.filesource = dlg.GetPath()
            self.control1FileSourceText.SetValue(self.filesource)
	    if (not (self.filesource == "")):
		self.button3Extract.Enable(True)
		self.extractEnable = True
	    else:
		self.button3Extract.Enable(False)
		self.extractEnable = False
        dlg.Destroy()

        
  def OnPSTSourceTextChange (self,e):
        self.filesource = self.control1FileSourceText.GetValue()
	if (not (self.filesource == "")):
		self.button3Extract.Enable(True)
		self.extractEnable = True
	else:
		self.button3Extract.Enable(False)
		self.extractEnable = False
        print (" dirdest = "+self.dirdest+" filesource= "+self.filesource +" searchtype = "+self.searchtype)
        


  def OnMextraction (self,e):
        self.searchtype = 'M'
        self.label4Sextraction.SetValue(False)
        print (" dirdest = "+self.dirdest+" filesource= "+self.filesource +" searchtype = "+self.searchtype)

        
  def OnSextraction (self,e):
        self.searchtype = 'S'
        self.label3Mextraction.SetValue(False)
        print (" dirdest = "+self.dirdest+" filesource= "+self.filesource +" searchtype = "+self.searchtype)
        
          

  def OnChooseDecodification (self,e):
        
        if (self.decodification):
          self.decodification = False
          self.label44OverwriteCodificated.Enable(False)
          self.label34SaveCodificated.Enable(False)
          print (" decodification: False")
        else:
          self.decodification = True
          self.label44OverwriteCodificated.Enable(True)
          self.label34SaveCodificated.Enable(True)
          print (" decodification: True")
        
  def OnChooseSaveCodificated (self,e):
        self.overwrite = False
        self.label44OverwriteCodificated.SetValue(False)
        self.label34SaveCodificated.SetValue(True)
        print (" overwrite: False")


  def OnChooseOverwriteCodificated (self,e):
        self.overwrite = True
        self.label44OverwriteCodificated.SetValue(True)
        self.label34SaveCodificated.SetValue(False)
        print (" overwrite: True")    

      
  def StartExtraction (self,e):
    
        self.running = True
    
	self.DisableButtons()
        
        try:
          worker = WorkingThreadExtraction(self, 1, self.filesource, self.defaultCasePathValue, self.searchtype,self.decodification,self.overwrite,self.casename)
          worker.start()
        except Exception, e:
          print "Error starting thread %s " % e
          
        
  def EndExtraction (self, e):
        print ("Search is over")
        
        self.running = False

	dlg = wx.MessageDialog( self, "The work [" + "Extraction" +   "] is done!", "Work done", wx.OK)
        result = dlg.ShowModal()
        dlg.Destroy()
	
	self.running = False

	#enable controls
	self.EnableButtons()
	self.SearchDone = True
        
# THREADS -------------------------------------------------------------------------------------------------------------



class ThreadEvent(wx.PyCommandEvent):
    """Event to signal that a count value is ready"""
    def __init__(self, etype, eid, value=None):
        """Creates the event object"""
        wx.PyCommandEvent.__init__(self, etype, eid)
        self._value = value

    def GetValue(self):
        """Returns the value from the event.
        @return: the value of this event

        """
        return self._value
        
class WorkingThread(threading.Thread):
    def __init__(self, parent, value, fs,dd,st,cn):
        """
        @param parent: The gui object that should recieve the value
        @param value: value to 'calculate' to
        """
        threading.Thread.__init__(self)
        self._parent = parent
        self._value = value
        
        #extra
        self.filesource=fs
        self.dirdest= dd
        self.searchtype = st
	self.casename = cn
	self.result = ''
        

    def run(self):
        """Overrides Thread.run. Don't call this directly its called internally
        when you call Thread.start().
        """
        print ("running with filesource %s dirdest %s searchtype %s and casename %s " % (self.filesource, self.dirdest, self.searchtype,self.casename))
        self.result = EMLseekanddestroyMODULE.moduleMain(self.filesource, self.dirdest, self.searchtype,self.casename)
        evt = ThreadEvent(myEVT_ENDWORK, -1, self._value)
        wx.PostEvent(self._parent, evt)





class WorkingThreadListExport(threading.Thread):
    def __init__(self, parent, value, fs,importexport,listctrlo):
        """     
        @param parent: The gui object that should recieve the value
        @param value: value to 'calculate' to
        """
        threading.Thread.__init__(self)
        self._parent = parent
        self._value = value
        
        #extra
        self.filesource=fs
        self.isImport = importexport
        self.lc = listctrlo
        

    def run(self):
        """Overrides Thread.run. Don't call this directly its called internally
        when you call Thread.start().
        """
        print ("running with filesource %s  isImport %d" % (self.filesource, self.isImport))
        if (self.isImport == 1):
           #it's an import to the list
           print ("it's an import")
	   
	   #open file
           f = open(self.filesource,'r')
           print ("___control 1")
	   indice=0
	   for line in f.read().split('\n'):
	
                    print ("____control 2")
		    #print line
		    #extraer los 3 parametros
		    #print line
		    #print indice
		    
		    if ('#'  in line):
			indice= 0
			keyword = ''
			directory = ''
			output = ''
		    elif (indice==0):
			keyword = line
			indice+=1
		    elif (indice==1):   
			directory = line
			indice+=1
		    elif (indice==2):   
			output = line
			indice+=1
  			print ("_____control 3")
  			print "_____gonna write to listctrl "+output+" "+keyword+" "+directory
			num_items = self.lc.GetItemCount()
			print ("_____control 3.1 getitemCount = %d" % num_items)
			self.lc.InsertStringItem(num_items, output)
    			print ("_____control 3.2 isnerting in listcontrol %s  %s" % (num_items,output))
    			self.lc.SetStringItem(num_items, 1, keyword)
    			print ("_____control 3.3 set string column 1")
    			self.lc.SetStringItem(num_items, 2, directory)
		        print ("_____control 3.4 set string column 2")
		        print "_____wrote to listctrl"+output+" "+keyword
		        print ("_____control 4")
			indice= 0
			keyword = ''
			directory = ''
			output = ''

           print ("___control 5")
           #close file
           f.close()
        else:
           #it's an export of the list
           print ("it's an export")
           
           #open file
           f = open(self.filesource,'w')
           
           # Gather all the list items in the listCtrl
           for row in range(self.lc.GetItemCount()):
              search1 = "\n".join([self.lc.GetItem(row, 1).GetText().encode("iso-8859-1"),self.lc.GetItem(row, 2).GetText().encode("iso-8859-1"),self.lc.GetItem(row, 0).GetText().encode("iso-8859-1")])
              search1 = "%s\n#\n" % search1
              #write to file (append)
              f.write(search1)

           
        
              
           
           #close file
           f.close()
        
        evt = ThreadEvent(myEVT_ENDWORK_EXPORTLIST, -1, self._value)
        wx.PostEvent(self._parent, evt)


class WorkingThreadReportCreate(threading.Thread):
    def __init__(self, parent, value,fs,dd,st,cn,keywordlist, combination, copyFilesOnReport):
        """     
        @param parent: The gui object that should recieve the value
        @param value: value to 'calculate' to
        """
        threading.Thread.__init__(self)
        self._parent = parent
        self._value = value
       

        #extra
        self.filesource=fs
        self.dirdest= dd
        self.searchtype = st
	self.casename = cn
	self.keywordlist = keywordlist
	self.combination = combination
	self.result = ''
	self.copyFilesOnReport = copyFilesOnReport
       

    def run(self):
        """Overrides Thread.run. Don't call this directly its called internally
        when you call Thread.start().
        """
	print "[WorkingThreadReportCreate]"
        self.result = EMLseekanddestroyMODULE.moduleMain(self.filesource, self.dirdest, "createreport",self.casename,self.keywordlist,self.combination,self.copyFilesOnReport)
        evt = ThreadEvent(myEVT_ENDWORK, -1, self._value)
        wx.PostEvent(self._parent, evt)
class WorkingThreadExtraction(threading.Thread):
    def __init__(self, parent, value, fs,dd,st,decode,overwrite,casename):
        """
        @param parent: The gui object that should recieve the value
        @param value: value to 'calculate' to
        """
        threading.Thread.__init__(self)
        self._parent = parent
        self._value = value
        
        #extra
        self.filesource=fs
        self.dirdest= dd
        self.searchtype = st
        self.decodification = decode
        self.overwrite = overwrite
        self.casename = casename

    def run(self):
        """Overrides Thread.run. Don't call this directly its called internally
        when you call Thread.start().
        """
        print ("running with filesource %s dirdest %s ans searchtype %s " % (self.filesource, self.dirdest, self.searchtype))
        EMLextractor.moduleMain(self.filesource, self.dirdest, self.searchtype)
        print (" readPST finished")
        if (self.decodification):
          print (" EMLDecoder starting...")
          dirdest2 = self.dirdest
          if (self.overwrite):
            dirdest2 = self.dirdest
          else:
            dirdest2 = self.dirdest + "_Decoded"
          EMLDecoder.moduleMain(self.dirdest, dirdest2,self.overwrite,self.casename)
          print (" EMLDecoder finished")
	  #bd insertion with dirdest2 -> se hace en EMLDecoder

	else:
	  #bd insertion with dirdest -> si no se ha decodificado hay que insertar en la bd las rutas de los ficehros sin decodificar
	  EMLextractor.dbWork ( self.dirdest,self.casename)
	  

	#end of the work
        evt = ThreadEvent(myEVT_ENDWORK, -1, self._value)
        wx.PostEvent(self._parent, evt)


#-------------------------------------MAIN------------------------------------------------------------------------
#threads
myEVT_ENDWORK = wx.NewEventType()
myEVT_ENDWORK_EXPORTLIST = wx.NewEventType()
EVT_ENDWORK = wx.PyEventBinder(myEVT_ENDWORK, 1)
EVT_ENDWORK2 = wx.PyEventBinder(myEVT_ENDWORK_EXPORTLIST , 2)

app = wx.App(False)
frame = MainWindow(None, "EMLseekanddestroy")
app.MainLoop()
